﻿﻿using DeviceCommons.DeviceMessages.Models;
using DeviceCommons.DeviceMessages.Models.V1;
using System.Buffers;
using DeviceCommons.DataHandling;

namespace DeviceCommons.DeviceMessages.Serialization.V2
{
    public class ProcessVersionData : IProcessVersion, IContextAwareParser
    {
        private ParsingContext? _context;

        public void Parser(IDeviceMessage model, ReadOnlySpan<byte> bytes)
        {
            ArgumentNullException.ThrowIfNull(model);
            
            // 设置上下文到子解析器
            if (_context != null && DeviceMessageSerializerProvider.ChildV2Par is IContextAwareParser contextAwareParser)
            {
                contextAwareParser.SetContext(_context);
            }
            
            var deviceTemp = DeviceMessageSerializerProvider.ChildV2Par.Parser(bytes[4..]);
            ArgumentNullException.ThrowIfNull(deviceTemp.ChildArray);
            model.MainDevice = deviceTemp.ChildArray[0];
            model.ChildDevice ??= new DeviceMessageChild();
            model.ChildDevice.ChildArray = deviceTemp.ChildArray.AsSpan()[1..].ToArray();
        }

        public ReadOnlySpan<byte> Serializer(IDeviceMessage model)
        {
            ArgumentNullException.ThrowIfNull(model);
            ArgumentNullException.ThrowIfNull(model.MainDevice);
            ArgumentNullException.ThrowIfNull(model.ChildDevice);
            ArgumentNullException.ThrowIfNull(model.ChildDevice.ChildArray);
            
            // 🔧 修复: 创建临时数组而不修改原始模型
            var childTemp = new IDeviceMessageInfo[model.ChildDevice.Count + 1];
            childTemp[0] = model.MainDevice;
            model.ChildDevice.ChildArray.CopyTo(childTemp, 1);
            
            // 🔧 修复: 创建临时的DeviceMessageChild对象，避免修改原始数据
            var tempChildDevice = new DeviceMessageChild { ChildArray = childTemp };
            
            var arrayBufferWriter = new ArrayBufferWriter<byte>();
            DeviceMessageSerializerProvider.HeaderV2Ser.Serializer(arrayBufferWriter, model.Header ?? new DeviceMessageHeader());
            DeviceMessageSerializerProvider.ChildV2Ser.Serializer(arrayBufferWriter, tempChildDevice);
            return arrayBufferWriter.WrittenSpan;
        }

        public void SetContext(ParsingContext context)
        {
            _context = context;
        }

        public ParsingContext? GetContext()
        {
            return _context;
        }
    }
}
